//
//  UIWindow+TouchVisualize.m
//  TouchDemo
//
//  Created by songruili on 2021/5/18.
//

#if kTouchVisualize

#import "UIWindow+TouchVisualize.h"
#import "JRSwizzle.h"
#import "UITouch+TouchVisualize.h"
#import <objc/runtime.h>

@implementation UIWindow (TouchVisualize)

#pragma mark - Public

+ (void)enableTouchVisualize
{
    if (!self.isTouchVisualize)
    {
        self.isTouchVisualize = YES;
        [self touchVisualizeSwizzleSendEvent];
    }
}

+ (void)disableTouchVisualize
{
    if (self.isTouchVisualize)
    {
        self.isTouchVisualize = NO;
        [self touchVisualizeSwizzleSendEvent];
    }
}

#pragma mark - Property

+ (void)setIsTouchVisualize:(BOOL)isTouchVisualize
{
    objc_setAssociatedObject(self, @selector(isTouchVisualize), @(isTouchVisualize), OBJC_ASSOCIATION_ASSIGN);
}

+ (BOOL)isTouchVisualize
{
    return [objc_getAssociatedObject(self, @selector(isTouchVisualize)) boolValue];
}

#pragma mark - Private

+ (void)touchVisualizeSwizzleSendEvent
{
    NSError *error = nil;
    if (![self jr_swizzleMethod:@selector(sendEvent:) withMethod:@selector(tv_sendEvent:) error:nil])
    {
        NSLog(@"%@", error);
    }
}

#pragma mark - Swizzle

- (void)tv_sendEvent:(UIEvent *)event
{
    [self tv_sendEvent:event];
    
    if (event.type == UIEventTypeTouches)
    {
        NSSet <UITouch *> *touches = [event allTouches];
        [touches enumerateObjectsUsingBlock:^(UITouch * _Nonnull obj, BOOL * _Nonnull stop) {
            switch (obj.phase)
            {
                case UITouchPhaseBegan:
                case UITouchPhaseMoved:
                {
                    [self.layer addSublayer:[obj updateVisualizeLayer]];
                }
                    break;
                case UITouchPhaseEnded:
                case UITouchPhaseCancelled:
                {
                    [obj.visualizeLayer removeFromSuperlayer];
                }
                    break;
                default:
                    break;
            }
        }];
    }
}

@end

#endif
